//
//  UserAccount.swift
//  SinaWeiBo
//
//  Created by tuyue on 16/3/10.
//  Copyright © 2016年 xueyang.co.ltd. All rights reserved.
//

import UIKit
import AFNetworking

private let userInfoKey = "cn.itcast.account"

class UserAccount: NSObject {

    
    /**
    *  1,字典转模型
    2，保存数据
    3，对外提供获取数据方法
    */
     
     //MARK: - 提供给外界的属性
     /**定义单例对象*/
    static let  sharedAccount = UserAccount()
    /**用于调用access_token，用户访问接口权限的标示*/
    var access_token:String?
    /**token的生命周期*/
    var expires_in:NSTimeInterval = 0 {
        didSet{
        expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    /**taken过期日期*/
    var expires_date:NSDate?
    /**用户id*/
    var uid:String?  
    /**用户昵称*/
    var name:String?
    
    /**用户头像*/
    var avatar_large:String?{
        didSet{
        headImageURL = NSURL(string: avatar_large ?? "")
        }
    }
    /**设置用户头像的URL*/
    var headImageURL: NSURL?
    
    
    /**计算型属性*/
    var userLogin:Bool {
    /**accsess_token不为空，就表示用户登录，为空就表示用户未登录*/
       
    return access_token != nil
    }
    
    override private init() {
        super.init()
        /**加载用户信息*/
        self.loadUserInfo()
    }
    
    /**过滤value不存在的方法*/
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    override var description:String{
        let keys = ["access_token","expires_in","uid","name","avatar_large","expires_date"]
        let accountDict = self.dictionaryWithValuesForKeys(keys)
        
        return accountDict.description
    }
    
    private func keyboardChanged(){
    
    }
    
    
//    /**注册通知*/
//    private func registerNotification(){
//    NSNotificationCenter.defaultCenter().addObserver(<#T##observer: AnyObject##AnyObject#>, selector: <#T##Selector#>, name: <#T##String?#>, object: <#T##AnyObject?#>)
//    }
}


//MARK: - 账户相关的业务逻辑扩展
//MARK: - 保存数据，获取数据
extension UserAccount{

    func saveUserInfo(dict: [String : AnyObject]){
    /**给当前对象KVC设置初始值--未登录状态--登录状态*/
        self.setValuesForKeysWithDictionary(dict)
        /**保存当前对象的所有属性*/
        let userDefaults = NSUserDefaults.standardUserDefaults()
        /**获取当前对象的字典信息*/
        let keys = ["access_token","expires_in","uid","name","avatar_large","expires_date"]
        let accountDict = self.dictionaryWithValuesForKeys(keys)
        userDefaults.setObject(accountDict, forKey: userInfoKey)
        /**同步沙盒*/
        userDefaults.synchronize()
        /**打印保存的地址*/
//        print(NSHomeDirectory())
    }
    
    
    func loadUserInfo(){
    /**从偏好设置中获取用户字典信息*/
        guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(userInfoKey) as? [String: AnyObject] else {
        return
        }
        /**将字典信息转换数据模型*/
        self.setValuesForKeysWithDictionary(dict)
//        print(dict)
        
        /**判断过期时间是否和当前时间相同，比较结果按照降序排列，若果相同，返回过期，不同*/
        if self.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
        print("正常")
        }else{
        print("已过期")
        self.access_token = nil
        }
    }
    
}


/**用户账户相关的所有网络请求*/
extension UserAccount{
    //MARK: - 发起网络请求用于获取accessToken
    /**将获取的code用于获取accessToken*/
    func loadAccessToken(code:String, finished: (isSuccess: Bool)->()){
        /**请求地址*/
        let urlString = "https://api.weibo.com/oauth2/access_token"
        /**拼接参数字典*/
        
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        /**创建AFHTTPSessionManager对象*/
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            //            print(result)
            /**获取token*/
            guard let dict = result as? [String: AnyObject] else{
//                SVProgressHUD.showErrorWithStatus("数据格式错误")
                finished(isSuccess: false)
                return
            }
            self.loadUserInfo(dict, finished: finished)
            }) { (_, error) -> Void in
                print(error)
        }
        
    }
    
    private  func loadUserInfo(dict: [ String : AnyObject ],finished: (isSuccess: Bool)->()){
        /**token是用户访问接口权限的一个时效性的标识*/
         /**根据获得的dict来获取token*/
        let access_token = dict["access_token"] as! String
        /**获取uid*/
        let uid = dict["uid"] as! String
        /**获取用户信息的接口URL*/
        let urlString = "https://api.weibo.com/2/users/show.json"
        /**创建参数数组*/
        let parameters = ["access_token":access_token,"uid":uid]
        /**穿件AFN对象*/
        let AFN = AFHTTPSessionManager()
        /**发送获取用户信息的请求*/
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            guard var userInfoDict = result as? [String: AnyObject] else {
                finished(isSuccess: false)
//                SVProgressHUD.showErrorWithStatus("数据格式错误")
                return
            }
            /**合并字典*/
            for (k,v) in dict{
                userInfoDict[k] = v
            }
            /**保存字典到沙盒*/
            UserAccount.sharedAccount.saveUserInfo(userInfoDict)
            //             UserAccount.sharedAccount.loadUserInfo()
            finished(isSuccess: true)
            
            }) { (_, error ) -> Void in
                /***/
                finished(isSuccess: false)
                print(error)
        }
        
    }
}
